<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> 
<title> GeoCode Sample User Interface V1.0.012 </title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="imagetoolbar" content="no"/>

<script type="text/javascript" src="../../static/js/prototype_1.6.1.js"></script>
<script type="text/javascript" src="../../static/js/xml2json.js"></script>
<script type="text/javascript" src="http://apis.daum.net/maps/maps.js?apikey=ba76c348c625d0c91b99b2962f1371590046e1f4" charset="utf-8"></script>

<script>

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

String.prototype.replaceAll = function( searchStr, replaceStr )
{
	var temp = this;
	
	while( temp.indexOf( searchStr ) != -1 )
	{
	temp = temp.replace( searchStr, replaceStr );
	}
	
	return temp;
}

function parseXml(xml) {
   var dom = null;
   if (window.DOMParser) {
      try { 
         dom = (new DOMParser()).parseFromString(xml, "text/xml"); 
      } catch (e) { 
          dom = null; 
      }
   } else if (window.ActiveXObject) {
      try {
         dom = new ActiveXObject('Microsoft.XMLDOM');
         dom.async = false;
         if (!dom.loadXML(xml)) { 
        	// parse error ..
            window.alert(dom.parseError.reason + dom.parseError.srcText);
         }
      }catch (e) {
          dom = null; 
      }
   } else { 
      alert("oops");
   }
   return dom;
}


function requestGeoCode() {  

	var messageUi = $( 'messageUi' );
	var locationUi = $( 'locationUi' );

	messageUi.value = "";
	locationUi.value = "";

	var url ="./M3100_GeoCodeAct.jsp" ;

	var qInput = $( 'qInput' );

	var params =  {
	   "a"            : "" 
	 , "q" : qInput.value 
	};

	var onSuccessListener = requestGeoCodeSuccessListener ;
	var onFailureListener = requestGeoCodeFailureListener ;

	callAjax( url, params, onSuccessListener, onFailureListener );
	
}

function requestGeoCodeFailureListener( transport ) {
	var msg = "서버가 응답하지 않습니다.!";
    alert( msg );
}

function requestGeoCodeSuccessListener( transport ) {
	var localDebug = false ; 
	
    // ajax transport 검증
	var readyState = transport.readyState;

    /* transport.readyState  
	 
	0 UNINITIALIZED 오브젝트는 작성되어 있으나 아직 초기화되어 있지 않다.(open()이 불리지 않았음)  
	1  LOADING 오브젝트가 작성되었으나 아직 send()가 불리지 않았다. 
	2   LOADED send()가 불렸지만 ststus와 header가 아직 도착하지 않았다.  
	3  INTERACTIVE  data일부를 받았다. 
	4   COMPLETED data전부를 받았다. 완전한 데이터가 이용가능 
	*/

	if ( readyState == 3 ) { // 데이터를 완전히 받았을 경우...
		alert( "ERROR: 서버로 부터 데이터를 완전히 받지 않았습니다.!" ); 
	} else if( readyState == 4 ) { // 데이터를 완전히 받았을 경우...
		//alert( "서버로 부터 데이터를 완전히 받았습니다.!" ); 
		// go on 
	} else {
		alert( "ERROR: transport.readyState = " + readyState );
	}
	// end of ajax transport 검증
	
	if( localDebug ) {  
        alert( transport.responseText  );
    }

    var serverResponse = transport.responseText.trim();
    serverResponse = serverResponse.replaceAll( " />" , "/>" );

    if( serverResponse.length < 1 ) {
        // if server response is blank
        alert( "ERROR-001: 지도코드 서버의 응답이 없거나 느립니다!" );
        return;
    } 
    

	// convert xml server response to json object  
	
	var xml = null ;
	if( true ) {
		xml = parseXml( serverResponse );
	} else {
		xml = transport.responseXML;
	} 

	var jsonText = xml2json( xml ); 

	jsonText = jsonText.replace( "undefined", "" ); // debugging code

	var jsonObj = eval("(" + jsonText + ")"); 

	// end of converting xml server response to json object

	var item = jsonObj.resultSet.item ;

	// process message list
	
	var messageText = "";

    try {
    	var resultMessageList = item.resultMessageList.resultMessage; 
		for( var i = 0, iLen = resultMessageList.length; i < iLen; i ++ ) {
			messageText += resultMessageList[ i ] ; 
			messageText += ( i < iLen - 1 ? "\n" : "" );
		}
	} catch( e ) {
		if( false ) { 
		     alert( "응답 메시지가 없습니다.!" );
		}
	}

	var messageUi = $( 'messageUi' );
	messageUi.value = messageText;
	
	// end of processing message list

	// process locaton
	
	var x = item.x;
	var y = item.y;

	var location = "x: " + x + ", y: " + y;

	var locationUi = $( 'locationUi' );
	locationUi.value = location;  

	var addrDesc = "";
	if( true ) { 
		addrDesc += ( item.h1 != null ) ? ( item.h1 + " " ) : "" ;
		addrDesc += ( item.h23 != null ) ? ( item.h23 + " " ) : "" ;
		addrDesc += ( item.h4 != null ) ? ( item.h4 + " " ) : "" ;
		addrDesc += ( item.h5 != null ) ? ( item.h5 + " " ) : "" ;
		addrDesc += ( item.h6 != null ) ? ( item.h6 + " " ) : "" ;
		
		var san = item.san;
		if( san != null && san > 0 ) {
			addrDesc += "산 ";
		}

		if( item.juBun != null ) { 
			addrDesc += item.juBun;
			
			var buBun = item.buBun;
			if( buBun != null && buBun.length > 0 ) {
				addrDesc += "-" + buBun;
			}
			addrDesc += "번지" ;
		}

		addrDesc += ( item.bldName != null ) ? ( " " + item.bldName ) : "" ;
		addrDesc += ( item.bldDong != null ) ? ( " " + item.bldDong ) : "" ;
		addrDesc += ( item.bldHo != null ) ? ( " " + item.bldHo ) : "" ;
	}

	setMapLocation( x, y, addrDesc ); 

	// end of processing location 
	
} 

function setMapLocation( x, y, addrDesc ) { 

	x = parseFloat( "" + x );
	y = parseFloat( "" + y );  
	
	var text = addrDesc;
	
	//mark 추가
    var icon = new DIcon("http://localimg.daum-img.net/localimages/07/2008/map/i_mks_b1.gif", new DSize(13, 16)); 

    icon.src = "http://localimg.daum-img.net/localimages/07/2008/map/i_mks_b1.gif";
    var infoWin = new DInfoWindow( text, { show: true } ) ;
    var mark = new DMark(new DPoint(x, y), { mark: icon, draggable: true, infowindow_mouseover : true, label: null, infowindow: infoWin } );

    map.clearOverlay(); // 지도위에 표시된 모든 overlay들을 제거한다.
    
    map.addOverlay(mark);  // mark Overlay

    map.setCenter(new DPoint(x, y), 4); //한 번에 이동

}

function callAjax( url , params, onSuccessListener, onFailureListener ) { 
    new Ajax.Request(
        url ,
        {
            asynchronous: true ,
            method: 'POST',  
            encoding: 'UTF-8' ,
            "parameters" : params ,  
            onCreate: function() {  
            } , 
            onComplete: function() { 
            } , 
            onFailure: onFailureListener
            ,
            onSuccess:  onSuccessListener
        }
    ) 
}
</script>
</head>
 
<body>
  <table>
      <tr>
    <td>
       주소
    </td>
    <td>
        <input id="qInput" type="text" size="55" value="부산시 금정구 남산동 84-22"/>
        <input type="button" value='요청' onclick="requestGeoCode();"/>
    </td>
   </tr>
   <tr>
      <td>메시지</td> 
      <td><textarea id="messageUi" style="width:400px; height:100px; background-color: white; "></textarea></td>
   </tr>
   <tr>
      <td>위치</td> 
      <td>
            <input id="locationUi" type="text" size="61" value=""/>
      </td>
   </tr>
   <tr> 
      <td colspan="2">
		<div id="map" style="width:600px; height:300px;">다음 지도</div>
		<script type="text/javascript">
	        if( true ) { 
				var map = new DMap("map", { point: new DLatLng(37.48879895934866, 127.03130020103005), level: 4 });
				map.setCoordinateType("wgs84");
				map.addControl(new DZoomControl());
	        }
		</script>
      </td>
   </tr> 
  </table>
</body>
</html>
